//
//  LoginViewController.swift
//  fsapp
//
//  Created by zguang on 17/7/27.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD
class LoginViewController: UIViewController {

    
    let loginview = loginView(type:"login")
   let usd = UserSave()
    var sessionID = ""
    
    lazy var returnButton:UIButton = {
        let btn = UIImageView()
        btn.frame = CGRect(x: getWidth(width: 24), y: CGFloat(getHeight(62)), width: getWidth(width: 25), height: getHeight(45));
        btn.image = UIImage(named:"return")
        let back = UIButton()
        back.frame = CGRect(x: getWidth(width: 0), y: 0, width: getWidth(width: 70), height: getHeight(100));
        back.addSubview(btn)
        return back
    }()
    
    
    public func clearUsd(){
      usd.deleteInfo()
    }
    
    override func viewDidLoad() {
        self.view.backgroundColor = UIColor.white
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
        self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
         self.navigationItem.title = "登录"
         self.navigationController?.navigationBar.isTranslucent = false
      //  self.navigationController?.navigationBar.backgroundColor = naviColor
        self.navigationController?.navigationBar.barTintColor = naviColor
        self.view.addSubview(loginview.BackView)
        self.loginview.registerButton.addTarget(self, action: #selector(touchRegist), for: .touchUpInside)
        self.loginview.visibleButton.addTarget(self, action: #selector(hidePassword(_:)), for: .touchUpInside)
        self.loginview.loginNow.addTarget(self, action: #selector(loginNow), for: .touchUpInside)
        self.loginview.forgetButton.addTarget(self, action: #selector(touchFind), for: .touchUpInside)
        
       
        let item = UIBarButtonItem(image: #imageLiteral(resourceName: "return2"), style: .plain, target: self, action: #selector(returnFunc))
        //item.imageInsets = UIEdgeInsets.init(top: 10, left: 25, bottom: 10, right: -5)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.leftBarButtonItem = item

        
        //self.view.addSubview(self.returnButton)
        
        
        
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.loginview.passwordText.resignFirstResponder()
        self.loginview.phoneText.resignFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - basic func
    
    func returnFunc(){
      self.dismiss(animated: true, completion: nil)
    }
    
    
    func touchRegist(){
        //隐藏返回文字
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
      self.navigationController?.pushViewController(RegistViewController(), animated: true)
    }
    
    func touchFind(){
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        self.navigationController?.pushViewController(FindPasswordViewController(), animated: true)
    }
    
    
    
    func hidePassword(_ btn:UIButton){
         btn.isSelected = !btn.isSelected
        if btn.isSelected{
            self.loginview.passwordText.isSecureTextEntry = false
        }else{
         self.loginview.passwordText.isSecureTextEntry = true
        }
    }
    
    
    func loginNow(){
        let phone = self.loginview.phoneText.text
        let password = self.loginview.passwordText.text
        if phone == ""||password == ""{
            let alert = UIAlertController(title: "提示", message: "用户名或密码不得为空", preferredStyle: .alert)
            let action = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alert.addAction(action)
            self.present(alert, animated: true, completion: nil)
        }else{
        
             Alarequest()
          //  GetCookieStorage()
        //  print( GetCookieArray())
         /*   let str = String(describing: GetCookieArray())
            print(str)
            let cookie = HTTPCookie(properties: [HTTPCookiePropertyKey(rawValue: "name"):GetCookieByName(cookieName: "__cfduid")!])
            print(cookie)
            self.sessionID =
                "PHPSESSID=" + GetCookieByName(cookieName: "__cfduid")!
           // print(GetCookieByName(cookieName: "__cfduid"))
         */
        }
        
        
    
    
    }
    
    
    
    
//MARK: - 网络请求
    
    
    public func GetCookieStorage()->HTTPCookieStorage{
        return HTTPCookieStorage.shared
    }
    public  func GetCookieArray()->[HTTPCookie]{
        
        let cookieStorage = GetCookieStorage()
        let cookieArray = cookieStorage.cookies
        if let arr = cookieArray{
            return arr as! [HTTPCookie]
        }
        else{
            return []
        }
    }
    /// 获取Cookie值
    public func GetCookieByName( cookieName:String)->String?
    {
        let cookieArray:[HTTPCookie] = GetCookieArray()
        var value:String?
        if cookieArray.count > 0
        {
            for cookie in cookieArray
            {
                if cookie.name == cookieName
                {
                    value = cookie.value
                    break
                }
            }
        }
        return value
    }
    
    
    
    func Alarequest(){
        let account:String = self.loginview.phoneText.text!;
        let password:String = self.loginview.passwordText.text!
        
        let url = "http://dahan-api.heiyou.net/index.php/home/user/login"
        let paramdic =
            ["account":account,
             "password":password,
            "machine_code":String(describing: idfa)
             ]
        
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
                
            }else{
                print("网络异常")
            }
     // print(response.response?.allHeaderFields)
            
            
           if let cookies =  HTTPCookieStorage.shared.cookies{
           // print(cookies)
            self.saveCookies(response: response)
//          let usr = UserDefaults.standard
          //  usr.set(cookies as [String:String], forKey: "savedCookies")
           //  UserDefaults.standard.synchronize()
            print(cookies)
                for cookie in cookies{
                self.sessionID = String(cookie.name)+("=") + String(cookie.value)
                }
            }else {
                print("登录出错,未获取到sessionID")
                return
            }
            
            if self.sessionID == "" {
                print("登录出错,未获取到sessionID")
                 //return
            }
            
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                DispatchQueue.main.async {
                    if(js["status"]==200){
                      //  saveCookies(response: response)
                        //bo = true
                        print(js)
                        if let vip = js["result"]["vip"].string{
                            if let sex = js["result"]["sex"].string{
                                self.usd.saveInfo(js["result"]["id"].string!, js["result"]["account"].string!, js["result"]["password"].string!,vip, js["result"]["name"].string!,sex,js["result"]["img"].string!,js["result"]["rest"].string!,js["result"]["consume"].string!, js["result"]["status"].string!,sessionID: self.sessionID)
                            }else{
                                
                                self.usd.saveInfo(js["result"]["id"].string!, js["result"]["account"].string!, js["result"]["password"].string!,vip, js["result"]["name"].string!,"",js["result"]["img"].string!,js["result"]["rest"].string!,js["result"]["consume"].string!, js["result"]["status"].string!,sessionID: self.sessionID)
                            }
                        }else{
                            if let sex = js["result"]["sex"].string{
                                self.usd.saveInfo(js["result"]["id"].string!, js["result"]["account"].string!, js["result"]["password"].string!,"0", js["result"]["name"].string!,sex,js["result"]["img"].string!,js["result"]["rest"].string!,js["result"]["consume"].string!, js["result"]["status"].string!,sessionID: self.sessionID)
                            }else{
                                
                                self.usd.saveInfo(js["result"]["id"].string!, js["result"]["account"].string!, js["result"]["password"].string!,"0", js["result"]["name"].string!,"",js["result"]["img"].string!,js["result"]["rest"].string!,js["result"]["consume"].string!, js["result"]["status"].string!,sessionID: self.sessionID)
                            }
                            
                        }
                        //print(bo)
                        print(self.usd.readInfo())
                       SVProgressHUD.dismiss(withDelay: 1)
                      SVProgressHUD.showSuccess(withStatus: "登录成功")
                        
                        let cus = LoadViewController()
                        let index = cus.CusTomTabBar()
                        self.present(index, animated: true, completion: nil)
                        
                    }
                        
                    else{
                        if js["status"] == 1000{
                            let alert = UIAlertView(title: "用户不存在", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                        else if js["status"] == 1001{
                            let alert = UIAlertView(title: "密码错误", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                        else if js["status"] == 0 {
                            let alert = UIAlertView(title: "服务器出错", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                        else {
                            //15960225752
                            let alert = UIAlertView(title: js["msg"].string!, message: "", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                        
                    }
                }
            
            }}
       //  print(self.usd.readInfo())
       // print(account+password)
    
    
    
    }
    
    
    func saveCookies(response: DataResponse<Any>) {
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.response?.url
        //let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        if let cookies =  HTTPCookieStorage.shared.cookies{
        var cookieArray = [[HTTPCookiePropertyKey: Any]]()
        for cookie in cookies {
            cookieArray.append(cookie.properties!)
        }
        UserDefaults.standard.set(cookieArray, forKey: "savedCookies")
        UserDefaults.standard.synchronize()
        //print(cookieArray)
        }
    }

    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
